package repository

import (
	"errors"
	"gitee.com/wendyRose/common"
	"gitee.com/wendyRose/payment/domain/model"
	"github.com/jinzhu/gorm"
)

type IPaymentRepository interface {
	InitTable() error
	AddPayment(payment *model.Payment) (int64, error)
	UpdatePayment(payment *model.Payment) error
	DeletePaymentByID(paymentID int64) error
	FindPaymentByID(paymentID int64) (*model.Payment, error)
	FindAllPayment() ([]model.Payment, error)
}

type PaymentRepository struct {
	mysqlDb *gorm.DB
}

func NewPaymentRepository(db *gorm.DB) IPaymentRepository {
	return &PaymentRepository{mysqlDb: db}
}

func (p *PaymentRepository) InitTable() error {
	return p.mysqlDb.CreateTable(&model.Payment{}).Error
}

func (p *PaymentRepository) AddPayment(payment *model.Payment) (int64, error) {
	db := p.mysqlDb.FirstOrCreate(payment, model.Payment{
		PaymentName:   payment.PaymentName,
		PaymentSID:    payment.PaymentSID,
		PaymentStatus: payment.PaymentStatus,
		PaymentImage:  payment.PaymentImage,
	})
	if db.Error != nil {
		common.Error(db.Error)
	}
	if db.RowsAffected == 0 {
		return 0, errors.New("新增支付配置失败")
	}
	return payment.ID, nil
}

func (p *PaymentRepository) UpdatePayment(payment *model.Payment) error {
	return p.mysqlDb.Model(payment).Update(payment).Error
}

func (p *PaymentRepository) DeletePaymentByID(paymentID int64) error  {
	return p.mysqlDb.Where("id = ?", paymentID).Delete(&model.Payment{}).Error
}

func (p *PaymentRepository) FindPaymentByID(paymentID int64) (payment *model.Payment, err error) {
	payment = &model.Payment{}
	return payment, p.mysqlDb.First(payment, paymentID).Error
}

func (p *PaymentRepository) FindAllPayment() (paymentAll []model.Payment, err error) {
	return paymentAll, p.mysqlDb.Find(&paymentAll).Error
}




